package com.a3dweijing.wetouch2.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.a3dweijing.wetouch2.R;
import com.a3dweijing.wetouch2.base.BaseActivity;
import com.a3dweijing.wetouch2.bean.CheckCode;
import com.a3dweijing.wetouch2.bean.LoginMsg;
import com.a3dweijing.wetouch2.datainterface.Getdataimpl;
import com.a3dweijing.wetouch2.datasave.Singleton;
import com.a3dweijing.wetouch2.tools.SharedPreUtil;
import com.a3dweijing.wetouch2.tools.Str2MD5;
import com.google.gson.Gson;

/**
 * Created by yxd on 2017/10/13.
 */

public class SetPasswordActivity extends BaseActivity
{
    private TextView phoneNumTxv;
    
    private TextView timerTxv;
    
    private EditText checkCodeEdt;
    
    private EditText passwordEdt;
    
    private EditText invite;
    
    private ImageView back;
    
    private TextView nextBtn;
    
    private String phoneStr;
    
    private String checkcodeStr;
    
    private Handler handler;
    
    private CountDownTimer timer;
    
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setpassword);
        
        back = (ImageView)findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Intent intent = new Intent(SetPasswordActivity.this, LoginActivity.class);
                startActivity(intent);
                finish();
            }
        });
        checkcodeStr = getIntent().getStringExtra("code");
        phoneStr = getIntent().getStringExtra("phone_number");
        phoneNumTxv = (TextView)findViewById(R.id.setpassword_phonenum_txv);
        timerTxv = (TextView)findViewById(R.id.setpassword_timer_txv);
        invite = (EditText)findViewById(R.id.invite);
        timerTxv.setEnabled(false);
        checkCodeEdt = (EditText)findViewById(R.id.setpassword_check_code_edt);
        passwordEdt = (EditText)findViewById(R.id.setpassword_password_edt);
        nextBtn = (TextView)findViewById(R.id.setpassword_next_btn);
        phoneNumTxv.setText(phoneStr);
        nextBtn.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                String check = checkCodeEdt.getText().toString();
                if (check != null && check.length() == 6)
                {
                    if (Str2MD5.MD5(check).equals(checkcodeStr))
                    {
                        String pwd = passwordEdt.getText().toString();
                        if (pwd != null && pwd.length() >= 6 && pwd.length() <= 18)
                        {
                            new RegisterThread(phoneStr, pwd, invite.getText().toString()).start();
                            startPopupwindow(getBaseContext(), "注册中...");
                            // 获取邀请码
                            
                        }
                        else
                        {
                            Toast.makeText(getBaseContext(), "请输入6-18位的密码的密码", Toast.LENGTH_SHORT).show();
                        }
                    }
                    else
                    {
                        Toast.makeText(getBaseContext(), "验证不正确", Toast.LENGTH_SHORT).show();
                    }
                }
                else
                {
                    Toast.makeText(getBaseContext(), "验证不正确", Toast.LENGTH_SHORT).show();
                }
                
            }
        });
        timerTxv.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                timer.start();
                timerTxv.setEnabled(false);
                new getcheckcodeThread(phoneStr).start();
            }
        });
        handler = new Handler()
        {
            @Override
            public void handleMessage(Message msg)
            {
                super.handleMessage(msg);
                switch (msg.what)
                {
                    case 100:
                        endPopupwindow();
                        LoginMsg loginMsg = new Gson().fromJson(msg.obj.toString(), LoginMsg.class);
                        if (loginMsg.isFlag())
                        {
                            Singleton.getInstance().setUser(loginMsg.getUser());
                            SharedPreUtil.put(getBaseContext(), "username", phoneStr);
                            SharedPreUtil.put(getBaseContext(), "userpwd", passwordEdt.getText().toString().trim());
                            Intent intent = new Intent(SetPasswordActivity.this, MainActivity.class);
                            startActivity(intent);
                            finish();
                        }
                        else
                        {
                            Toast.makeText(getBaseContext(), "网络异常，请稍后再试!!", Toast.LENGTH_SHORT).show();
                        }
                        break;
                    case 200:
                        CheckCode code = new Gson().fromJson(msg.obj.toString(), CheckCode.class);
                        if (code.isFlag())
                        {
                            checkcodeStr = code.getCode();
                        }
                        Log.e("--", msg.obj.toString());
                        break;
                    case 404:
                        Toast.makeText(getBaseContext(), msg.obj.toString(), Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        };
        timer = new CountDownTimer(60000, 1000)
        {
            
            @Override
            public void onTick(long millisUntilFinished)
            {
                timerTxv.setText((millisUntilFinished / 1000) + "s");
            }
            
            @Override
            public void onFinish()
            {
                timerTxv.setEnabled(true);
                timerTxv.setText("获取验证码");
            }
        };
        timer.start();
    }
    
    private class RegisterThread extends Thread
    {
        String phone_number;
        
        String password;
        
        String userReferralcode;
        
        public RegisterThread(String phone_number, String password, String userReferralcode)
        {
            this.phone_number = phone_number;
            this.password = password;
            this.userReferralcode = userReferralcode;
        }
        
        @Override
        public void run()
        {
            super.run();
            String resulet = new Getdataimpl().remotRegisters(phone_number, password, userReferralcode);
            Log.e("--", resulet);
            if (resulet != null && resulet.length() > 7)
            {
                handler.sendMessage(handler.obtainMessage(100, resulet));
            }
            else
            {
                handler.sendMessage(handler.obtainMessage(404, "网络繁忙，请稍后再试"));
            }
        }
    }
    
    private class getcheckcodeThread extends Thread
    {
        String phone_number;
        
        public getcheckcodeThread(String phone_number)
        {
            this.phone_number = phone_number;
        }
        
        @Override
        public void run()
        {
            super.run();
            String resulet = new Getdataimpl().remotGetCheckCode(phone_number);
            Log.e("--", resulet);
            if (resulet != null && resulet.length() > 7)
            {
                handler.sendMessage(handler.obtainMessage(200, resulet));
            }
            else
            {
                handler.sendMessage(handler.obtainMessage(404, "网络繁忙，请稍后再试"));
            }
        }
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
            Intent backOne = new Intent(SetPasswordActivity.this, LoginActivity.class);
            startActivity(backOne);
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }
}
